Public class customConvertLeadExtension 
{
//Converts lead to an account,contact and opty
    private final Lead ld;
    public id leadid; 
    public Id opty{get;set;}
    public Id Acct{get;set;}
    public Id Cont{get;set;}
    public Id NonConvLead {get;set;}
    public Lead ConvLead {get;set;}
    Public String ldcheck {get;set;}
    //public List<Contact> SecContacts {get{ return ContactList;} set;}
    public boolean EnableConvert{get;set;}
    private Profile profile;
    public String errorMessage {get;set;}
    
    public customConvertLeadExtension(ApexPages.StandardController controller) 
    {
     //default error message for convert lead 
     errorMessage ='You cannot initiate order for this lead since an account already exists with the same phone number or same Company Name';  
    
      leadid = ApexPages.currentPage().getParameters().get('leadid');
      //system.debug(leadid );
      ldcheck = ApexPages.currentPage().getParameters().get('wincheck');
      //when called from lead page leadid is null
      if(leadid == null)
         leadid = ApexPages.currentPage().getParameters().get('id');
         
      ld = [select id, name, recordtypeid from lead where id = :leadid];
   }
   
    //check if AAS lead, redirect to Opportunity wizard screen.. 
    private PageReference redirectToWizardforAASLeads()
    {
          //for advanced ad solution users redirect to opportunity wizard page
       string AASLeadrecordTypeId = RecordTypeHelper.GetRecordTypeId('Lead', 'Advanced Ad Solutions');  
       string localLeadrecordTypeId = RecordTypeHelper.GetRecordTypeId('Lead', 'Local Advertiser'); 
       string  redirectURL;
        
       System.Debug('defaultrecordTypeId' + AASLeadrecordTypeId + ld.recordTypeId + localLeadrecordTypeId);
       
       //redirect to opportunity wizard page for AAS profiles       
       if(AASLeadrecordTypeId.Contains(ld.recordTypeId))   {
           redirectURL = '/apex/SelectMasterClient?leadId=' + leadId + '&retURL=/' + leadId + '&ent=Lead';                 
       }
       else if(!localLeadrecordTypeId.Contains(ld.recordTypeId)){
           redirectURL='/lead/leadconvert.jsp?retURL=/' + leadId +'&id= '+ leadId;
       }
       else  //for local advertiser do not redirect
            return null;
            
       System.Debug('redirectURL' + redirectURL);
       PageReference convertLeadPage = new PageReference(redirectURL);
       return convertLeadPage;
       
    }

      public PageReference stdLeadConvert()
     {   
            
            //Only some AAS profiles can convert lead..this is required because convert lead is  a custom button in AAS page layout
           this.profile=[Select p.Name From Profile p where p.Id=:UserInfo.getProfileId()];
           System.Debug('profile' + profile.Name);
           if (profile.Name == 'AAS Billing Import'  || 
                 profile.Name == 'AAS Billings-Collections' || 
                 profile.Name == 'Advanced Ad Solutions (AAS Visitor)' ||
                 profile.Name == 'Advanced Ad Solutions (IEM)' ||
                 profile.Name == 'Advanced Ad Solutions-BNI CMR') {          
              errorMessage = 'Sorry, your current profile does not allow you to create New Accounts or Opportunities';
              EnableConvert =false;
              NonConvLead =leadId;
              return null;
           }
             //for all other AAS profiles redirect to opportunity wizard..
             PageReference convertLeadPage = redirectToWizardforAASLeads();
             
             if(convertLeadPage != null)
                return convertLeadPage;
              
              //for non AAS recordtype continue with convert lead (SFA OOR)                       
                   ConvLead = [select id,Win_Back_Account__c,OORTelesalesCampaign__c,OOR_Contact_Convert_Map__c,Primary_Owner__c,cleanphonetext__c,Owner.Name,County__c,LeadSource,Company,Name,Disposition__c,ownerId,Secondary_Owner__c , Projected_close_date__c,convertedAccountId,convertedOpportunityId,convertedContactId from lead where id = :leadid];
                   NonConvLead = ConvLead.id;
                   if(ConvLead.Disposition__c == 'Signed Contract' || ConvLead.Disposition__c =='Sale'){
                        /* added for fix */
                        ID localAccRecordTypeID = RecordTypeHelper.GetRecordTypeID('Account', 'Local OOR Customer');

List<Account> accnt =   [select RecordTypeId from account where (cleanphonetext__c =:ConvLead.cleanphonetext__c or cleanprimaryphone_text__c =:ConvLead.cleanphonetext__c) and RecordTypeId=:localAccRecordTypeID and (cleanprimaryphone_text__c!='' or cleanprimaryphone_text__c!=null) and (cleanphonetext__c!='' or cleanphonetext__c !=null) and Type__c != 'Win-Back' limit 1];

                        //system.debug('AAAAAA'+accnt + ConvLead.cleanphonetext__c);
                        if(accnt.size()==0 ){
                        Database.LeadConvert lc = new database.LeadConvert();
                        lc.setLeadId(leadid);
                     //Code added for Win-Back Lead Convert
                        if(ldcheck == '1'){
                            lc.setAccountId(ConvLead.Win_Back_Account__c);
                            if((ConvLead.OOR_Contact_Convert_Map__c != null) || (ConvLead.OOR_Contact_Convert_Map__c != '')){
                                lc.setContactId(ConvLead.OOR_Contact_Convert_Map__c);
                            }
                        } //Code Ended for Win-Back Lead Convert
                        //lc.setDoNotCreateOpportunity(true);
                        LeadStatus convertStatus = [Select Id, MasterLabel,IsConverted from LeadStatus where IsConverted=true limit 1];
                        lc.setConvertedStatus(convertStatus.MasterLabel);
                        Database.LeadConvertResult lcr = Database.convertLead(lc);
                        System.assert(lcr.isSuccess());
                       EnableConvert = true;
                        //Links to records after conversion
                         ConvLead = [select id,FirstName,LastName,OORTelesalesCampaign__c,street,city,state,PostalCode,County__c,LeadSource,Name,Company,Product_Family__c,Projected_Revenue__c,Projected_close_date__c,Disposition__c,ownerId,Owner.Name,Secondary_Owner__c , convertedAccountId,convertedOpportunityId,convertedContactId from lead where id = :leadid];
                        //system.debug(ConvLead);
                        Opty = ConvLead.convertedOpportunityId;
                        Cont = ConvLead.convertedContactId;
                        Acct = ConvLead.convertedAccountId;
                        
                        contact primeContact = [select FirstName,LastName,primary_indicator__c from contact where id=:cont];
                        primeContact.primary_indicator__c = true;
                        primeContact.FirstName= ConvLead.FirstName;
                        primeContact.LastName = ConvLead.LastName;
                        try{update primeContact;}
                        catch(DMLException e){
                        System.debug('Exception in Contact update'+e);
                        } 
                        ID localAdvertiserRecordTypeID = RecordTypeHelper.GetRecordTypeID('Opportunity', 'SFA-OOR Lead Order');
                        ID localAdvertiserRecordTypeIDContact = RecordTypeHelper.GetRecordTypeID('Contact','Local Advertiser');
                        account acc = [select Name,OwnerId,type__c,county__C,Business_Address__c,City__c,State__c,zip__c from account where id=:acct];
                        acc.Name = ConvLead.Company;
                        if(ldcheck == '1'){
                        acc.type__c = 'Win-Back';
                        }
                        else{
                        acc.type__c = 'Prospect';
                        }
                        acc.zip__c = ConvLead.PostalCode;
                        acc.State__c= ConvLead.State;
                        acc.County__c = ConvLead.County__c;
                        acc.City__c = ConvLead.City;
                        acc.Business_Address__c = ConvLead.Street;
                        acc.OOR_Update_Check__c = true;
                        acc.RecordTypeId = localAccRecordTypeID;
                        acc.Account_Owner_Details__c = acc.OwnerId;
                        try{
                        update acc;      
                        }
                        catch(DMLException e){
                        System.debug('Exception in Account update'+e);
                        }                 
                        
                        Opportunity Oppty = [select LeadSource,CampaignId,OORTelesalesCampaign__c,Opportunity_Type__c,Projected_close_date__c,Owner.Name,contact_name__c,Opportunity_Amount__c,CloseDate ,Secondary_Owner__C,recordTypeId from Opportunity where id=:Opty];
                        system.debug('@@@@@@@@@'+oppty.Owner.Name);
                        Oppty.recordTypeId = localAdvertiserRecordTypeID;
                        Oppty.contact_name__c = Cont;
                        Oppty.LeadSource = ConvLead.LeadSource;
                        Oppty.Secondary_Owner__C = ConvLead.Secondary_Owner__C;
                        Oppty.Product_Family__c = ConvLead.Product_Family__c;
                        Oppty.StageName = 'Signed Contract';
                        Oppty.OORTelesalesCampaign__c=ConvLead.OORTelesalesCampaign__c; 
						Oppty.Opportunity_Amount__c = ConvLead.Projected_Revenue__c;
                        Oppty.OOR_Update_Check__c = true;
  
                      //Oppty.Primary_Owner__c ='Test Owner';
                        Oppty.Revenue_mo__c = ConvLead.Projected_Revenue__c;
                        Oppty.Opportunity_Type__c = 'New';
                        
                        if(ConvLead.Projected_close_date__c != null)
                        Oppty.Projected_close_date__c = ConvLead.Projected_close_date__c;
                        else
                        Oppty.Projected_close_date__c = system.today();
                        try{
                        update Oppty;
                        }
                          catch(DMLException e){
                        System.debug('Exception in Account update'+e);
                        }
                        //Updating secondary Contacts with the new Account Id
                        List<Contact> contactList = [select Id,AccountId from Contact where Lead__c =:leadid];
                        //List<Contact> ContactList = new List<Contact>();
                        for(Contact Con:contactList){
                        Con.AccountId = Acct;
                        Con.recordtypeid= localAdvertiserRecordTypeIDContact;
                        //contactList.add(Con);
                        }
                        If(contactList.size()>0){
                        //system.debug('Contact to be created'+ContactList);
                        try{
                        update contactList;
                                                
                        }
                        catch(DMLexception e){
                        system.debug('Exception due to Secondary contact list'+e);
                        }
                        }
                        //carry forward notes from lead to opty
                        List<Notes__c> LeadNotes = new List<Notes__c>();
                        LeadNotes = [select opportunity__c from Notes__c where lead__c = :ld.Id];
                        if(LeadNotes.Size() > 0){
                            integer i;
                            for(i=0; i < LeadNotes.Size(); i++){
                            LeadNotes[i].Opportunity__C = Opty ;
                            }
                            try{
                        Update LeadNotes;
                        }
                        catch(DMLException e){
                        System.debug('Exception in Account update'+e);
                        }
                        }
                      } 
                      else{
                           EnableConvert = false; }                                              
                       return null;     
                 }
                 else{
                  EnableConvert = false;
                   return null;  }
                   }



            /* test method for code coverage */
            
            static testMethod void testConvertOper()
             {
            /* create a test lead to be used for the code execution */
            
            List<Lead> leads = new List<Lead>();
            ID localContactRecID = RecordTypeHelper.GetRecordTypeID('Contact', 'Local Advertiser');
            ID localLeadRecID = RecordTypeHelper.GetRecordTypeID('Lead', 'Local Advertiser');
            
            Lead ld = new Lead(RecordTypeId=localLeadRecID,Company ='Test Demo',FirstName='John',LastName='Smith',Phone='8989898989',Disposition__c='Ready for Order');
            //Lead ld2 = new Lead(RecordTypeId=localLeadRecID,Company ='Test Demo2',FirstName='John2',LastName='Smith2',Phone='8989894589',Disposition__c='New Entry',Status='New');
            //Lead ld3 = new Lead(RecordTypeId=localLeadRecID,Company ='Test Demo3',FirstName='John3',LastName='Smith3',Phone='8989894559',Disposition__c='Wrong listing',Status='Invalid Lead');
            //Lead ld4 = new Lead(RecordTypeId=localLeadRecID,Company ='Test Demo4',FirstName='John4',LastName='Smith4',Phone='89898944459',Disposition__c='No Sale',Status='Closed');
            //Added by Venkat
            //ld2.Disposition__c = 'Signed Contract'; 
            //End Venkat
            insert ld;
            //insert ld2;
            //insert ld3;
            //insert ld4;           
            
            /* created an opportunity to cover the code for Create Notes */
            Account accObj = new Account(Name='Test Account');
            Account accObj2 = new Account(Name='Test Account2');
            
            accObj.type__c = 'Prospect'; 
            insert accObj;
            accObj2.type__c = 'Prospect';
            insert accObj2;           
            
            // Contact insert to cover the code for the trigger 
            
            Contact cnt = new Contact();
            cnt.IsPrimary_Contact__c=true;
            cnt.AccountId=accObj.Id;
            cnt.RecordTypeId=localContactRecID;
            cnt.FirstName = 'Krish';
            cnt.LastName='Suni';
            cnt.Phone='5555555';
            
            insert cnt;
            
            Contact cnt3 = new Contact();
            cnt3.IsPrimary_Contact__c=true;
            cnt3.RecordTypeId=localContactRecID;
            cnt3.AccountId=accObj2.Id;
            cnt3.FirstName = 'Krish3';
            cnt3.LastName='Suni3';
            cnt3.Phone='5555555';
                        
            insert cnt3;            
            
            Opportunity opp = new Opportunity();
            opp.AccountId= accObj.Id;
            opp.Name='Test Opp';
            opp.LeadSource='Internet';
            Date curr = Date.today();
            opp.CloseDate=curr;
            opp.Projected_close_date__c=curr;
            opp.StageName='New';
            opp.Most_Recent_Notes__c='testcoverage';
            //insert opp;
            
            Notes__c callnotes = new Notes__c();
            callnotes.Lead__c=ld.Id;
            callnotes.Account__c=accObj.Id;
            //callnotes.Opportunity__c=opp.Id;
            insert callnotes;
            
            ApexPages.StandardController thecontroller = new ApexPages.StandardController(ld);
            //ApexPages.StandardController thecontroller2 = new ApexPages.StandardController(ld2);
            //Venkat added
            PageReference pg = new PageReference('/apex/ConvertLead');
            pg.getParameters().put('leadid',ld.id);
            
            Test.setCurrentPageReference(pg);
            //Venkat End
            customConvertLeadExtension controller = new customConvertLeadExtension(thecontroller);
            //customConvertLeadExtension controller2 = new customConvertLeadExtension(thecontroller2);
            controller.stdLeadConvert();
           // controller2.stdLeadConvert();
                            
             }            
            }